<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    function __construct()
    {
        $this->user = new User();
    }

    function index(){
        return view('admin.index');
    }

    function userShow(){
        return view('admin.users');
    }
    //获取用户列表
    function userList(){
        $userinfo = DB::table('users')->select('id','name','created_at','email')->get();
        $data = [
            "code"=>0,
            "msg"=>"获取成功",
            "count"=>count($userinfo),
            "data"=>$userinfo
        ];

        return json_encode($data);
    }

    function userAdd(Request $request){
        if($request->method()=="POST"){
            $validator = Validator::make($request->all(),[
                'name'=>'required|max:255',
                'email'=>'required|email',
                'password'=>'required|min:6|max:32',
            ]);
            if($validator->fails()){
                return redirect(route("useradd"))->withErrors($validator)->withInput();
            }

            $this->user->name = $request->get('name');
            $this->user->email = $request->get('email');
            $this->user->password = bcrypt($request->get('password'));

            $bool =  $this->user->save();
            if ($bool){
                return redirect(route('usershow'));
            }

        }
        return view('admin.useradd');
    }
    function userUpdate(Request $request,$id){
        if($request->method()=="POST"){

        }
        //通过id 获取用户信息
        $user = $this->user->where('id',$id)->first()->toArray();
        return view('admin.userupdate',compact('user'));
    }
}
